package com.wfh.mianshiji.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wfh.mianshiji.annotation.AuthCheck;
import com.wfh.mianshiji.common.BaseResponse;
import com.wfh.mianshiji.common.DeleteRequest;
import com.wfh.mianshiji.common.ErrorCode;
import com.wfh.mianshiji.common.ResultUtils;
import com.wfh.mianshiji.constant.UserConstant;
import com.wfh.mianshiji.exception.BusinessException;
import com.wfh.mianshiji.model.dto.user.*;
import com.wfh.mianshiji.model.entity.User;
import com.wfh.mianshiji.model.vo.UserVo;
import com.wfh.mianshiji.service.UserService;
import com.wfh.mianshiji.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: UserController
 * @Author wangfenghuan
 * @Package com.wfh.mianshiji.controller
 * @Date 2025/10/30 15:44
 * @description: 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public BaseResponse<UserVo> userLogin(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request) {
        // 参数校验
        String userAccount = loginRequest.getUserAccount();
        String userPassword = loginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword) || userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.getBaseMapper().selectList(userService.getQueryWrapper(loginRequest));
        if (users.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户不存在");
        }
        User user = users.getFirst();
        String password = user.getUserPassword();
        boolean bcrypted = DigestUtil.bcryptCheck(userPassword, password);
        if (!bcrypted) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "密码错误");
        }
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        Map<String, Object> userVoMap = new HashMap<>();
        userVoMap.put("user", userVo);
        String s = jwtUtil.genToken(userVoMap);
        userVo.setToken(s);
        request.getSession()
                .setAttribute(UserConstant.USER_LOGIN_STATE, userVo);
        return ResultUtils.success(userVo);
    }

    @PostMapping("/register")
    public BaseResponse<Boolean> userRegister(@RequestBody UserRegisterRequest registerRequest) {
        // 参数校验
        String userAccount = registerRequest.getUserAccount();
        String userPassword = registerRequest.getUserPassword();
        String checkPassword = registerRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)
                || userAccount.length() < 4
                || userPassword.length() < 8
                || !userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.getBaseMapper().selectList(userService.getQueryWrapper(registerRequest));
        if (!users.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "账号已经存在");
        }
        User user = BeanUtil.copyProperties(registerRequest, User.class);
        user.setUserPassword(DigestUtil.bcrypt(userPassword));
        return ResultUtils.success(userService.save(user));
    }

    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> addUser(@RequestBody UserAddRequest addRequest) {
        String userAccount = addRequest.getUserAccount();
        String userPassword = addRequest.getUserPassword();
        if (StringUtils.isAnyEmpty(userAccount, userPassword) || userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.getBaseMapper().selectList(userService.getQueryWrapper(addRequest));
        if (!users.isEmpty()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "账号已经存在");
        }
        String bcrypt = DigestUtil.bcrypt(userPassword);
        User user = BeanUtil.copyProperties(addRequest, User.class);
        user.setUserPassword(bcrypt);
        return ResultUtils.success(userService.save(user));
    }

    @PostMapping("/delById")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> delById(@RequestBody DeleteRequest deleteRequest) {
        Long id = deleteRequest.getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.removeById(id));
    }

    @PostMapping("/delByIds")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> delByIds(@RequestBody UserDeleteRequest deleteRequest) {
        List<Long> ids = deleteRequest.getIds();
        if (ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(userService.removeByIds(ids));
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        Long id = userUpdateRequest.getId();
        String userPassword = userUpdateRequest.getUserPassword();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String bcrypt = "";
        if (StringUtils.isNotEmpty(userPassword)) {
            bcrypt = DigestUtil.bcrypt(userPassword);
        }
        User user = BeanUtil.copyProperties(userUpdateRequest, User.class);
        user.setUserPassword(bcrypt);
        try {
            userService.getBaseMapper().updateById(user);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return ResultUtils.success(true);
    }

    @PostMapping("/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<UserVo>> getUserByPage(@RequestBody UserQueryRequest queryRequest) {
        long current = queryRequest.getCurrent();
        long pageSize = queryRequest.getPageSize();
        if (ObjUtil.isEmpty(current) || ObjUtil.isEmpty(pageSize)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<User> page = userService.page(new Page<>(current, pageSize), userService.getQueryWrapper(queryRequest));
        List<User> records = page.getRecords();
        List<UserVo> collect = records.stream().map(user -> BeanUtil.copyProperties(user, UserVo.class)).toList();
        return ResultUtils.success(collect);
    }

    @GetMapping("/getCurrentUser")
    public BaseResponse<UserVo> getCurrentUser(HttpServletRequest request){
        return ResultUtils.success(userService.getCurrentUser(request));
    }

    @GetMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return ResultUtils.success(true);
    }

    @GetMapping("/get/{userId}")
    public BaseResponse<UserVo> getUserById(@PathVariable("userId") Long userId) {
        User byId = userService.getById(userId);
        if (byId == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        return ResultUtils.success(BeanUtil.copyProperties(byId, UserVo.class));
    }
}
